package com.xianggu.register;

import com.xianggu.protocol.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author chengjy
 * @date 2025/3/9
 */
public class LocalServeRegister {

    private static boolean isFirstLoad = false;

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        List<URL> provider = getRegister("Provider");
        System.out.println();
    }

    private static final String fileLocal = "D:\\XiangGu\\XiangGuRpc\\LocalServeFile\\";
    public static void register(String serviceName, String hostName, Integer prot) throws IOException {
        List<URL> urls = new ArrayList<>();
        URL url = new URL(hostName, prot);
        urls.add(url);
        // 本地注册表
        String filePath = fileLocal + serviceName + ".txt";
        File file = new File(filePath);
        // 判断文件是否存在！
        if (file.exists()) {
            // 读取并写入新的
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
                List<URL> oldUrls = (List<URL>) ois.readObject();
                // 判断是否已经存在
                boolean isExist = false;
                for (URL oldUrl : oldUrls) {
                    if(hostName.equals(oldUrl.getHostName() ) && prot.equals(oldUrl.getProt())){
                        isExist = true;
                    }
                }
                if (!isExist) {
                    // 不存在 需要添加
                    urls.addAll(oldUrls);
                }else{
                    // 存在 不需要更新列表
                    urls = oldUrls;
                }
                ois.close();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }else{
//            file.mkdirs();
        }
        // 创建文件并写入

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(urls);
        oos.close();
    }

    public static List<URL> getRegister(String serviceName) throws IOException, ClassNotFoundException {
        String filePath = fileLocal + serviceName + ".txt";
        File file = new File(filePath);
        if (file.exists()) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
                List<URL> oldUrls = (List<URL>) ois.readObject();

                ois.close();
                return oldUrls;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }else{
            throw new IOException(serviceName + "服务未注册");
        }
    }
}
